<template>
    <div id="trainReport" class="compReport" :style="{fontSize:fontSize+'px'}">
        <report-header @downloadReports="downloadReports" @zoomIn="zoomIn" @zoomOut="zoomOut" :title="reportInfo.name" :scale="scale" :disSub="disSub" :disDownloadReport="disDownloadReport">
		</report-header>
      <div class="reportContent">
      		<cover :style="pageMargin" :title="reportInfo.name" :data="coverData"></cover>
      		<page class="page2" :style="pageMargin" :title="reportInfo.name" :configAddress="configAddress" :configInstruction="configInstruction">
				<!--slot--页面主体部分-->
				<div id="scoreAnalysis" class="chart" style="height:100%;width:100%"></div>
			</page>
			<page class="page3" :style="pageMargin" type="table" :title="reportInfo.name" v-for="(item,index) in rankListPageNumArr" :key="index" :configAddress="configAddress" :configInstruction="configInstruction">
				<!--slot--页面主体部分-->
				<div :style="{height:getContentHeight()+'px'}">
					<h4>排行总榜</h4><small>(得失分:攻击得分/防守得分/异常得分/异常失分，攻击次数:总次数/成功次数/失败次数/被攻击次数)</small>
					<Table stripe :columns="reportCol" :data="item.data" class="rankTable"></Table>
				</div>
			</page>
      </div>
    </div>
</template>

<script>
	import HighCharts from 'highcharts'
	import highchartsMore from 'highcharts/highcharts-more';
	import * as SeriesLabel from 'highcharts/modules/series-label';
	import html2canvas from 'html2canvas'
	import jsPDF from 'jspdf'
	import mixin from "@/components/report/mixinFun.js"
	//接口
	import {getReport,getTrainById} from '@/api/train'
	//组件
	import reportHeader from "@/components/report/reportHeader.vue"
	import cover from "@/components/report/cover.vue"
	import page from "@/components/report/page.vue"
	export default {
		name: 'trainReport',
		components: {
			page,
			cover,
			reportHeader
		},
		mixins: [mixin],
		data(){
			return {
				sceneId:this.$route.query.id,
				scale:1,
				fontSize:14,
				disSub:false,
				reportInfo:{},
				pageMargin:{},
				sysLogo:'',
				showSysLogo:true,
				disDownloadReport:true,
				// 表格
				reportCol: [
					{
						key: 'teamName',
						title: '团队名称',
						per:0.25
					},
					{
						key: 'totalScore',
						title: '总分',
						per:0.25
					},
					{
						key: 'totalScore',
						title: '得失分',
						per:0.25
					},
					{
						key: 'totalScore',
						title: '攻击次数',
						per:0.25
					}
				],
				rankList:[],
				rankListPageNumArr:[],
			}
		},computed: {
			coverData: function() {
				let {
					startTime,
					endTime,
					userCount,
					creatorName,
					teamCount
				} = this.reportInfo;
				return [{
					value: startTime,
					title: '开始时间'
				}, {
					value: endTime,
					title: '结束时间'
				}, {
					value: creatorName,
					title: '创建者'
				}, {
					value: (teamCount || 0) + '个',
					title: '参赛团队'
				}, {
					value: (userCount || 0) + '人',
					title: '参赛人数'
				}, ]
			},
		},
		mounted() {
			this.setStyle();
			this.getTrainDetail();
			window.onresize = () => {
				this.disDownloadReport = true;
				this.setStyle();
			}
		},
		beforeDestroy() {

		},
		methods: {
			setStyle() {
				let width = (window.innerHtml || document.documentElement.clientWidth);
				this.fontSize = width / 1519 * 14;
				if(this.fontSize < 10) {
					this.fontSize = 10;
				}
				this.setPageMargin();
				//this.getRankPage();
			},
			initReportCol() {
				this.reportCol = [{
					key: 'teamName',
					title: '团队名称',
					per: 0.25
				}, {
					key: 'totalScore',
					title: '总分',
					per: 0.25
				}, {
					key: 'totalScore',
					title: '得失分',
					render: (h, params) => {
						return h('span', (params.row.attackScore || 0) + "/" + (params.row.defenseScore || 0) + "/" + (params.row.exceptScore || 0) + "/" + (params.row.exceptLostScore || 0))
					},
					per: 0.25
				}, {
					key: 'totalScore',
					title: '攻击次数',
					render: (h, params) => {
						return h('span', (params.row.totalCount || 0) + "/" + (params.row.attackCount || 0) + "/" + (params.row.failCount || 0) + "/" + (params.row.defenseFailedCount || 0))
					},
					per: 0.25
				} ];
			},
			getRankPage() {
				this.initReportCol();
				if(this.rankList.length > 0) {
					this.rankListPageNumArr = this.getTablePageData(this.reportCol, this.rankList);
				}
				this.$nextTick(() => {
					this.disDownloadReport = false;
				});
			},
			// 数据
			getTrainDetail(){ //是否需要切换步骤
				getTrainById(this.sceneId).then(res => {
					if(res.data.code === 1){
						this.reportInfo = res.data.data;
						console.log( res.data.data)
						this.generateReport();
					}else{
						this.$Message.error(res.data.message)
					}
				})
			},
			//生成报告
			generateReport() {
				let _this = this;
				getReport(this.sceneId).then(data => {
					if (data.data.code == 1) {
						let examReportInfo = data.data.data;
						//this.rankList = examReportInfo.rankList;
						// this.getRankPage();
						Object.assign(this.reportInfo, data.data.data);
						// this.$nextTick(() => {
						// 	this.drawChart();
						// });
					}else{
						this.$Message.error(data.data.message);
					}
				})
			},
			downloadReports(){
				this.disDownloadReport = true;
				document.documentElement.scrollLeft = 0;
				document.documentElement.scrollTop = 0;
				let docs = document.getElementsByClassName("page");
				let pdf = new jsPDF('p', 'pt', 'a4');
				this.pageDataArr = [];
				let proArr = Array.from(docs).map((doc,index) => {
					return this.htmlToCanvas(doc,index);
				})
				Promise.all(proArr).then(data => {
					for(let i = 0; i< this.pageDataArr.length;i++){
						let contentWidth = data[0].width;
						let contentHeight = data[0].height;
						//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
						let imgWidth = 595;
						let imgHeight = 595 / contentWidth * contentHeight;
						pdf.addImage(this.pageDataArr[i], 'JPEG', 0, 0, imgWidth, imgHeight);
						if(i < docs.length - 1){
							pdf.addPage();
						}
					}
					setTimeout(() => {
						pdf.save(this.reportInfo.name + "报告.pdf");
						this.disDownloadReport = false;
					},2000)
				})
			},
			htmlToCanvas(doc,index){
				return new Promise((resolve,reject) => {
					const box = window.getComputedStyle(doc);
					// 获取DOM 节点计算后宽高
					const width = box.width.replace('px','')
					const height = box.height.replace('px','')
					// 获取像素比
					console.log(window.devicePixelRatio);
					const scaleBy = window.devicePixelRatio > 1 ? window.devicePixelRatio : 1;
					html2canvas(doc,{
						scale:window.devicePixelRatio *2,
						width,
						height,
						scrollX:0,
						scrollY:0
					}).then((canvas) => {
					let pageData = canvas.toDataURL('image/jpeg', 1.0);
					this.pageDataArr[index] = pageData;
					resolve(canvas);
					}).catch(error => {

					})
				})
			},
			downloadReport(doc) {
				const box = window.getComputedStyle(doc);
				// 获取DOM 节点计算后宽高  取到的内容是385.993px
				const width = box.width.replace('px','')
				const height = box.height.replace('px','')
				// 获取像素比
				const scaleBy = window.devicePixelRatio > 1 ? window.devicePixelRatio : 1;
				html2canvas(doc,{
					api:window.devicePixelRatio *2,
					scale:window.devicePixelRatio *2,
					width,
					height
				}).then((canvas) => {
					var contentWidth = canvas.width;
					var contentHeight = canvas.height;
					//一页pdf显示html页面生成的canvas高度;
					var pageHeight = contentWidth / 592 * 842;
					//未生成pdf的html页面高度
					var leftHeight = contentHeight;
					//页面偏移
					var position = 0;
					//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
					var imgWidth = 595;
					var imgHeight = 595 / contentWidth * contentHeight;
					var pageData = canvas.toDataURL('image/jpeg', 1.0);
					var pdf = new jsPDF('p', 'pt', 'a4');
					//有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
					//当内容未超过pdf一页显示的范围，无需分页
					if (leftHeight < pageHeight) {
						pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
					} else {
						while (leftHeight > 0) {
						pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
						leftHeight -= pageHeight;
						position -= 842;
						//避免添加空白页
						if (leftHeight > 0) {
							pdf.addPage();
						}
						}
					}
					pdf.save(this.reportInfo.name + "报告.pdf");
				})
			},
			drawChart() {
				let _this = this;
				let users = [];
				let categorys = [];
				let indicatorData = [];
				if (_this.reportInfo.rankList.length <= 0) {
					return
				}
				let scoreOptione = {
					chart: {
						backgroundColor: 'transparent',
					},
					title: {
						text: '得分趋势统计',
						align:'left',
						y:this.fontSize * 0.8,
						style: {
							fontSize: this.fontSize * 0.8+'px',
							fontWeight:'bold',
							// color: 'red'   //这边是改标题的字体大小和颜色
						}
					},
				legend: {
					align: 'left',
					verticalAlign: 'top',
					itemStyle: {
						fontSize: this.fontSize * 0.6+'px',
						fontWeight:'normal',
						//	color: 'red'   //这边是改标题的字体大小和颜色
					}
				},
				xAxis: {
					categories: _this.reportInfo.rankList[0].scoreVO.map(score => score.scoreDate.split(" ")[1]),
					labels:{
						style:{
							fontSize:this.fontSize*0.6
						},
					},
				},
				plotOptions: {
					series: {
					label: {
					}
					}
				},
				yAxis: {
					title: {
					text: '得分'
					},
				},
				series: _this.reportInfo.rankList.map(user => {
					return {
					name: user.userName,
					data: user.scoreVO.map(score => score.score)
					}
				}),
				credits: {
					enabled: false
				}, //去掉地址
				exporting: {
					enabled: false
				}, //隐藏导出图片
				responsive: {
					rules: [{
					condition: {
						maxWidth: 500
					},
					chartOptions: {
						legend: {
						layout: 'horizontal',
						align: 'left',
						verticalAlign: 'top'
						}
					}
					}]
				}
				};
				SeriesLabel(HighCharts);
				HighCharts.chart('scoreAnalysis', scoreOptione);
			},
			zoomIn(){
				if(this.scale == 0.5){
					return
				}
				this.disDownloadReport = true;
				this.scale = this.accSub(this.scale,0.1);
				if(this.scale != 0){
					this.fontSize = this.fontSize - 0.5;
				}
				this.drawChart();
				this.setPageMargin();
				this.getRankPage();
			},
			zoomOut(){
				if(this.scale == 3){
					return
				}
				this.disDownloadReport = true;
				this.scale = this.accAdd(this.scale,0.1);
				if(this.scale != 0){
					this.fontSize = this.fontSize + 0.5;
				}
				this.drawChart();
				this.setPageMargin();
				this.getRankPage();
			}
		},
		destroyed() {

		}
	}
</script>

<style scoped src="@/components/report/report.css">
	
</style>
